/**
 * Created by wangkui on 2015/8/28.
 */
var express = require('express');
var router = express.Router();
var request = require('request');
var config = require('./../../config');
var huawei = require('./../../models/schema/huaweiSchema.js');
var url = require("url");
var async = require("async");
var http=require('http');
var fs = require("fs");
//设置标签
exports.setbiaozhu=function(req,res){
	var dayflag=new Date().getTime();
    huawei.find({"openid":req.body.openid},function(err,data){
        if(data.length===0){
            //定义一个新的数据集合：拆分前端传来的数据
            var newUser=new huawei({
                openid:req.body.openid,
                headimgurl:req.body.headimgurl,
                nickname:req.body.nickname,
                x:req.body.x,
                y:req.body.y,
                notes:req.body.notes,
                width:req.body.width,
                sex:req.body.sex,
				dayflag:dayflag
            });
            huawei.create(newUser, function(err, data) {
                if(err) { return handleError(res, err); }
                return res.jsonp(201, data);
            });
        }else{
            //更新坐标值
            huawei.update({"openid":req.body.openid},{$set:{x:req.body.x,y:req.body.y,notes:req.body.notes,width:req.body.width,dayflag:dayflag}},function(errs,datas){
                return res.jsonp(201, datas);
            });
        }
    });
};
//读取某个标签
exports.getbiaozhu=function(req,res){
    var openid=req.params.id;
    huawei.find({"openid":openid},function(err,data){
        return res.jsonp(data);
    });
};
//读取全部用户标注数据
exports.getAllbiaozhu=function(req,res){
    huawei.find({},function(err,data){
        return res.jsonp(data);
    }).limit(40).sort({"dayflag":-1});
};
//分页显示数据
exports.getbiaozhubyskip=function(req,res){

    var skip=req.query.skip || 0;
    var limit=req.query.limit || 6;
    var gendar = req.query.gendar || '';

    var id=req.params.id;
    var co_count; //记录总数
    var nums=limit*skip;  //返回数
    var where={};
    if(gendar!=''){
        where={sex:gendar};
    }
    huawei.count(where,function(err,total){
        if(err) { return handleError(res, err); }
        huawei.find(where,function(err,panotags){
            if(err) { return handleError(res, err); }
            var result = {total:total,skip:skip,data:panotags};
            return res.status(200).json(panotags);
        }).limit(limit).skip(skip);
    });
};
//根据Openid查询数据
exports.getbiaozhubyopenid=function(req,res){
    var id=req.params.id;
    huawei.find({"openid":id},function(err,data){
        return res.jsonp(data);
    });
};
//批量下载微信头像文件到服务器端
//}).limit(200);
exports.getwxheadimgs=function(req,res){
    var items='';
    huawei.find({},function(error,result){
        async.series({
            first:function(callback){
                for(var i=0;i<result.length;i++){
                    if(result[i].headimgurl==''){
                        items=items+',';
                    }else{
                        items=items+result[i].headimgurl+"图"+result[i].openid+",";
                    }
                }
                callback();
            }
        },function(err,results){
            return res.jsonp(downwximgs(items));
        });
    }).limit(100).sort({"dayflag":-1});
};
//下载微信头像到本地
function downimg(url_img,callback){
    var Arrs=url_img.split("图");
    var url="http://srv.bigpixel.cn/api/picture/get?url="+Arrs[0];
    var openid=Arrs[1];
    http.get(url, function(res){
        var imgData = "";
        res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
        res.on("data", function(chunk){
            imgData+=chunk;
        });
        res.on("end", function(){
            fs.readFile("./public/wxheadimgs/"+openid+".jpg",function(err){
                if(err){
                    //图片不存在则下载
                    fs.writeFile("./public/wxheadimgs/"+openid+".jpg", imgData, "binary", function(err){
                        if(!err){
                            callback();
                        }else{
                            callback();
                        }
                    });
                }else{
                    //图片存在则callback
                    callback();
                }
            });
        });
    });
};
//批量下载
function downwximgs(items,openids){
    var Arrs=items.split(",");
    async.eachSeries(Arrs,function(item,callback){
        if(item!=''){
            downimg(item,function(err,result){
                callback();
            });
        }else{
            callback();
        }
    },function(err){
        if(err){
            return "No";
        }else{
            return "yes";
        }
    });
};
//判断文件是否存在
function readimg(fsname){
    fs.readFile(fsname,function(err){
        if(err){
            return "no";
        }else{
            return "yes";
        }
    });
};

// 错误处理
function handleError(res, err) {
    return res.status(500).json(err);
}